﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;

namespace Excel4DB.Util
{
    public static class DTTrans
    {
        public static List<T> DataTable2List<T>(this DataTable dataTable)
        {
            if (dataTable == null && dataTable.Rows.Count > 0 && dataTable.Columns.Count <= 0)
                return null;
            var objType = typeof(T);
            object obj;
            PropertyInfo[] propertyInfos = objType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            List<string> propertyNames = propertyInfos.Select(pro =>
            {
                return pro.Name.ToUpper();
            }).ToList();
            if (propertyInfos.Length <= 0) return null;
            DataColumnCollection dataColumnCollection = dataTable.Columns;
            List<T> list = new List<T>();
            string columnName = string.Empty;
            foreach (DataRow row in dataTable.Rows)
            {
                obj = Activator.CreateInstance(objType);
                foreach (DataColumn column in dataTable.Columns)
                {
                    if (propertyNames.Contains(column.ColumnName.ToUpper()))
                    {
                        try
                        {
                            PropertyInfo property = objType.GetProperty(column.ColumnName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
                            property.SetValue(obj, row[column]);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception($"exception:this column type is {column.DataType.FullName}");
                        }
                    }
                }
                if (obj != null) list.Add((T)obj);
            }
            return list;
        }
    }
}
